package com.rpc.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToMessageDecoder;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;

import java.util.List;

/**
 * TODO:动态可配置解码器
 * @author yanzhuoleo
 * @version V1.0
 * @Description: 解码器
 * @date 2018-01-16-下午7:14
 */
@RequiredArgsConstructor
public class RpcDecode extends ByteToMessageDecoder {

    ISerialize iSerialize = new ProtostuffSerializeImpl();
    @NonNull
    private Class objectClass;


    /**
     * TODO:没有添加数据序列化类型
     * @param ctx
     * @param in
     * @param out
     * @throws Exception
     */
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        if (in.readableBytes() < 4) {
            return;
        }
        in.markReaderIndex();
        //读取数据长度
        int dataLength = in.readInt();

        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        in.readBytes(data);

        Object obj = iSerialize.deserialize(data, objectClass);
        out.add(obj);
    }
}
